package org.erepublik.company.controllers;

import org.erepublik.company.ECountry;
import org.erepublik.company.PriceIndex;
import org.erepublik.company.charts.CountryJSONDataCollector;
import org.erepublik.company.charts.ECountryDataType;
import org.erepublik.company.service.PriceIndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;

public class AbstractController {

    @Autowired // autumatycznie wstrzykiwany obiekt
    protected PriceIndexService countryDataService;
    
    public void fillModelMap(ModelMap model) {
        CountryJSONDataCollector dataProvider = 
                    (CountryJSONDataCollector) countryDataService.getDataCollctor("currency");
        PriceIndex[] data = dataProvider.getPricesIndex(ECountryDataType.NEW_CITIZENS, null);
        PriceIndex babyBoom = getCountryOfTheDay(data);

        model.addAttribute("countryOfTheDay", ((ECountry)babyBoom.getLocation() ) .getUrlName());
        model.addAttribute("countryOfTheDayNewCitizens", (int)babyBoom.getPrice());
    }

    
    private PriceIndex getCountryOfTheDay(PriceIndex[] data) {
        PriceIndex best = null;
        int mostNewCitizens = -1;
        for (PriceIndex priceIndex : data) {
            if (priceIndex.getLocation()!=null && priceIndex.getLocation() instanceof ECountry && priceIndex.getPrice()>mostNewCitizens) {
                best = priceIndex;
                mostNewCitizens = (int) best.getPrice();
            }
        }
        return best;
    }
    
}
